package com.yp.infrastructure.mvc.i18n;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.MessageSource;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.ServiceLoader;

@Slf4j
public class I18nMessageSourceService {

    private final ServiceLoader<IMessageSourceProvider> loader;
    private static final List<IMessageSourceProvider> list = new ArrayList<>();
    private static I18nMessageSourceService service;

    private I18nMessageSourceService() {
        loader = ServiceLoader.load(IMessageSourceProvider.class);
    }

    public static synchronized I18nMessageSourceService getInstance() {
        if (null == service) {
            service = new I18nMessageSourceService();
            service.initProviders();
        }
        return service;
    }

    private void initProviders() {
        try {
            for (IMessageSourceProvider iMessageSourceProvider : loader) {
                list.add(iMessageSourceProvider);
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }

    public String getMessage(String i18n, Locale locale) {
        String message = null;
        for (IMessageSourceProvider provider : list) {
            MessageSource source = provider.create().getI18nMessageSource();
            message = source.getMessage(i18n, null, i18n, locale);
            if (StringUtils.isNotEmpty(message)) break;
        }
        if (StringUtils.isEmpty(message)) return i18n;
        return message;
    }
}
